/* Controllers */

var appControllers = angular.module('appControllers', []);

// 微信服务请求
appControllers.controller('FwqqCtrl-wx', function($rootScope, $scope, $http,$ionicActionSheet, $ionicPopup,$ionicLoading,$state, Camera) {
	
	App.setScope($scope);
	App.userquery();

	window._pp_imageId = undefined;

	var user = Session.loadObject("user");
	if(user) {
		$scope.userinfo = user;
	}

	$scope.formData={};
	//$scope.formData.category='SERVICEREQ_CATEGORY_10';
	$scope.showimgdiv = false;
	$scope.file;


	$scope.selecttype = function(typename){
		$scope.formData.title=typename; //+"-微信";
	}

	$scope.eventDispatch = function() {

		if ($scope.formData.category == undefined || $scope.formData.category == '') {
			var alertPopup = $ionicPopup.alert({
				title : '输入错误',
				template : '请选择服务请求类型！'
			});
			return;
		}
		if ($scope.formData.description == undefined || $scope.formData.description == '') {
			var alertPopup = $ionicPopup.alert({
				title : '输入错误',
				template : '请输入描述！'
			});
			return;
		}
		if($scope.images_url && !$scope.formData.weixinPhotoId) {
			var alertPopup = $ionicPopup.alert({
				title : '暂缓提交',
				template : '照片还未上传完成,请过一会再提交服务请求！'
			});
			return;
		}

		var paramdata = {
			title : $scope.formData.title,
			category: $scope.formData.category,
			description : $scope.formData.description,
			files:$scope.fileids
		};
		if ($scope.formData.majorevent == true) {
			paramdata.majorevent = "Y";
		} else {
			paramdata.majorevent = "N";
		}
		var reqdata = {
			'method' : 'ServiceReqDispatch',
			'param' : JSON.stringify(paramdata),
			'weixinPhotoId': $scope.formData.weixinPhotoId, //'1rctdO_G1F97xF9AUx6ZbcksMVkD3EoiGll3tKC22Dao',
			'dataFrom' : 'weixin',
			'imageId': window._pp_imageId
		};

		 //alert(JSON.stringify(paramdata))
		 //return;

		App.ajaxPost(OpenAPI.requrl, $.param(reqdata), function(data){
			
			App.myNotice("新增服务请求成功");
			window.history.back();
		});
	}



$scope.fileChanged = function(ele){  
    $scope.files = ele.files;  
    $scope.$apply(); //传播Model的变化。  
}  
  
/** 
 * 文件上传 
 */  
$scope.upsave = function() {  
    var fd = new FormData();  
    var file = document.querySelector('input[type=file]').files[0];  
  
    var filename = $scope.files[0].name;  
  
    if(filename.length> 1 && filename ) {  
  
        var ldot = filename.lastIndexOf(".");  
        var type = filename.substring(ldot + 1);  
  
        if(type != "doc" && type !="docx") {  
            alert("文件类型不对，请重新选择");  
            //清除当前所选文件...  
        }else{  
  			alert('发送后台操作...')
        }  
    } 
}

  $scope.delimg = function() {
  	$('#wexinUploadImg').attr('src', '');
	$('#wexinUploadImgContainer').css('display', 'none');

	window._pp_imageId = undefined;

  	$scope.images_url = null;
  	$scope.formData.weixinPhotoId = null;
  }

});

// 服务请求列表
appControllers.controller('FwqqListCtrl', function($scope, $http, $state, $stateParams) {
	
	var p = {
		//"type" : "ServiceReq",
		"type" : "mobileRequest",
		"dbtype":'0'
	};
	var reqdata = {
		'method' : 'OrderList',
		'param' : JSON.stringify(p),
		'fromType': 'weixin'
	};

	if($stateParams.comment === "true") {
		reqdata.comment = true;
	}

	$scope.scrollItems = [];
	$scope.hasdata = true;

	var cacheusername = Store.loadObject("cacheusername");
	var expiredTime = 48*60*60*1000;
	//var processNames = ['准备服务请求','验证和记录','分派工单','实施交付/投诉处理','用户确认','关闭工单','绩效评分','归档','处理完成'];

	App.ajaxPost(OpenAPI.requrl, $.param(reqdata), function(data){
		for (var i = 0; i < data.object.length; i++) {
				var obj = data.object[i];
				/*if (obj.statu == "0") {
					obj.statuname = "未签收";
				} else if (obj.statu == "1") {
					obj.statuname = "已签收";
				} else if (obj.statu == "2") {
					obj.statuname = "已结束";
				} else {
					obj.statuname = "---";
				}*/
				if(obj && obj.endDate && obj.endDate > 0) {
					if(obj.hasOpinion || ((new Date()).getTime()-obj.endDate) > expiredTime) {
						obj.commentTitle = "查看评价";
						obj.commentReadonly = true;
					}else if(obj.starterLoginId == cacheusername) {
						obj.commentTitle = "我要评价";
						obj.commentReadonly = false;
					}
				}

				if(obj && obj.statuname) {
					obj.processName = obj.statuname;
					// var idx = processNames.indexOf(obj.statuname);
					// if(idx < 5 && idx >= 0) {
					// 	obj.processName = '正在处理';
					// }else if(idx >= 5) {
					// 	obj.processName = '处理完成';
					// }else {
					// 	console.log('无法识别的流程节点名称:' + obj.statuname);
					// }
				}

				$scope.scrollItems.push(obj);
			}
		if(data.object.length==0){
			$scope.hasdata = false;
		}
	});

	$scope.detail = function(obj) {

		$state.go('fuwuqingqiudetail', {
			'id' : obj.serialno
		});
	}

	$scope.comment = function(obj) {
		window._pp_commentReadonly = obj.commentReadonly;
		$state.go('add-comment', {
			'id' : obj.serialno
		});
	} 
});

// 服务请求详情查询
appControllers.controller('Fwqqdetail', function($scope, $http, $stateParams) {

	App.setScope($scope);
	App.userquery();
	var p = {
		"serialno" : $stateParams.id
	};
	
	var reqdata = {
		'method' : 'OrderQuery',
		'param' : JSON.stringify(p)
	};

	App.ajaxPost(OpenAPI.requrl, $.param(reqdata), function(data){

		var obj = data.object;
		var user = Session.loadObject("user");
		obj.typeName=App.getTypeName(obj.category);
		
		$scope.data = obj;
		$scope.data.serialno = $stateParams.id;

		if(user) {
			$scope.userinfo = user;
		}

		if(data.object.image) {
			$('#wexinDownloadImg').attr('src', data.object.image);
	  		$('#wexinDownloadImgContainer').css('display', 'block');
		}

    });

});

appControllers.controller('LoginFormCtrl', function($rootScope, $scope, $http,
		$location, $ionicPopup, $state) {

	$rootScope.isdisabled=false;

	var GetQueryString = function(name) {
	    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	    var r = window.location.search.substr(1).match(reg);
	    if(r!=null)return  unescape(r[2]); return null;
	}

	$scope.login = function(action) {

		// if(action == 'service') {
		// 	$state.go('fuwuqingqiu-wx');
		// }else if(action == 'history') {
		// 	$state.go('fuwuqingqiulist');
		// }else if(action == 'comment') {
		// 	$state.go('fuwuqingqiulist',{ comment: true });
		// }
		var token = GetQueryString('token');
		var reqdata = {
			token: token
		};

		// var _data= {'code':200,'result':true,'userObject':{"message":"","object":{"username":"43225","shizhuren":false,"email":"43225@Any3.com","sessionId":"DB31F576FF778BB004290B9285725F62","department":"管理创新与IT中心","name":"张慧波(Ella Zhang)","userid":"43225","replyPermission":false,"usertype":"0","mobile":"13708329853"},"code":200}}

		App.ajaxPost(OpenAPI.loginUrl, $.param(reqdata), function(_data){
			var data = _data.userObject;
			var usertype = data.object.usertype;
			var username = data.object.username;

	 		Session.saveObject("user", data.object);
			Session.saveObject("usertype", usertype);

			Store.saveObject("cacheusername",username);

			$rootScope.usertype = Session.loadObject("usertype");

			if(action == 'service') {
				$state.go('fuwuqingqiu-wx');
				// $state.go('add-comment');
			}else if(action == 'history') {
				$state.go('fuwuqingqiulist');
			}else if(action == 'comment') {
				$state.go('fuwuqingqiulist',{ comment: true });
			}
		});
	};

	$scope.genValidateCode = function() {
		var seed = new Array('abcdefghijklmnopqrstuvwxyz',
				'ABCDEFGHIJKLMNOPQRSTUVWXYZ', '0123456789'); // 创建需要的数据数组
		var idx, i;
		var result = ''; // 返回的结果变量
		for (i = 0; i < 4; i++) // 根据指定的长度
		{
			idx = Math.floor(Math.random() * 3); // 获得随机数据的整数部分-获取一个随机整数
			result += seed[idx].substr(Math.floor(Math.random()
					* (seed[idx].length)), 1);// 根据随机数获取数据中一个值
		}

		$scope.validatecode = result;

		Session.saveObject("validcode", result);

		return result; // 返回随机结果
	};

	$scope.validatecode = $scope.genValidateCode();
});

appControllers.controller('addCommentCtrl', function($scope, $http,$state, $stateParams,$ionicPopup) {
//angular.module('ItsmApp').controller('addCommentCtrl', function($scope, $http,$state, $stateParams) {

	var user = Session.loadObject("user");

	$scope.formData={
		grade: 4,
		serviceGrade: 4,
		isReadonly:  false
	};

	if($stateParams.id) {
		$scope.formData.isReadonly = window._pp_commentReadonly;

		App.ajaxPost(OpenAPI.getCommentUrl + $stateParams.id, {}, function(data){
			$scope.formData.grade = data.data.grade;
			$scope.formData.serviceGrade = data.data.serviceGrade;
			$scope.formData.content = data.data.content;
	    }, function(){
	    });
	}

	$scope.fixText=function(text,num){
		$('.add-commoent-prize span').removeClass('active');
		$('.add-commoent-prize span').eq(num).addClass('active');
		$scope.formData.content = text;
	}
	
	
	$scope.dosubmit=function(){

		if($scope.formData.content==undefined || $scope.formData.content.trim() == ""){
			var alertPopup = $ionicPopup.alert({
				title : '输入错误',
				template : '请输入内容描述'
			});
			return;
		}

		var p = {
			"userid" : user.userid,
			"username" : user.name
		};
		var reqdata = {
			'method' : 'NoteAdd',
			'param' : JSON.stringify(p),
			"content" : $scope.formData.content,
			"workOrderId": $stateParams.id,
			"grade": $scope.formData.grade,
			"serviceGrade": $scope.formData.serviceGrade
		};

		App.ajaxPost(OpenAPI.saveCommentUrl, $.param(reqdata), function(data){
			App.myNotice("提交成功");
			window.history.back()
			setTimeout(function(){
				window.location.href = '../itsm-prize/index.html'
			},800)
		});
	}

});
